<template>
	<div class="app-container">
		<!-- 筛选条件区域 -->
		<el-card>
			<el-form :model="filterForm">
				<el-row :gutter="20">
					<el-col :span="8">
						<el-form-item label="时间范围">
							<el-date-picker
								v-model="filterForm.dateRange"
								type="daterange"
								range-separator="至"
								start-placeholder="开始日期"
								end-placeholder="结束日期"
								value-format="YYYY-MM-DD"
								:picker-options="pickerOptions"
								@change="handleDateChange"
							/>
						</el-form-item>
					</el-col>
					<!-- <el-col :span="6">
						<el-form-item label="成本类型">
							<el-select
								v-model="filterForm.costTypes"
								multiple
								collapse-tags
								placeholder="全部类型"
								@change="handleTypeChange"
							>
								<el-option
									v-for="item in costTypeOptions"
									:key="item.dictValue"
									:label="item.dictLabel"
									:value="item.dictValue"
								/>
							</el-select>
						</el-form-item>
					</el-col> -->
					<el-col :span="6">
						<el-form-item>
							<el-button type="primary" @click="handleQuery">查询</el-button>
							<el-button @click="handleReset">重置</el-button>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
		</el-card>

		<!-- 关键指标卡片 -->
		<el-row
			class="mb-20 mt-2"
			style="display: flex; justify-content: space-between"
		>
			<el-col :span="4" v-for="(item, index) in costStats" :key="index">
				<el-card>
					<div class="card-content">
						<div class="card-title">{{ item.costCategory }}</div>
						<div class="card-value">
							¥ {{ item.costCount.toLocaleString() }}
						</div>
						<div
							class="card-compare"
							:class="{
								positive: String(item.proportion).includes('+'),
								negative: String(item.proportion).includes('-'),
							}"
						>
							占比 {{ item.proportion }}%
						</div>
					</div>
				</el-card>
			</el-col>
		</el-row>

		<el-card>
			<el-row :gutter="20" justify="end">
				<el-radio-group v-model="timeRangeType" @change="handleTimeRangeChange">
					<el-radio-button :value="1">本月</el-radio-button>
					<el-radio-button :value="2">本季</el-radio-button>
					<el-radio-button :value="3">本年</el-radio-button>
				</el-radio-group>
			</el-row>
		</el-card>

		<!-- 图表区域 -->
		<el-row :gutter="20" class="mb-20 mt-2">
			<!-- 成本构成分析 -->
			<el-col :span="12">
				<el-card>
					<template #header>
						<div class="chart-title">成本构成分析</div>
					</template>
					<div class="chart-container">
						<e-charts :option="costCompositionOption" />
					</div>
				</el-card>
			</el-col>

			<!-- 成本对比分析 -->
			<el-col :span="12">
				<el-card>
					<template #header>
						<div class="chart-title">成本对比分析 (2022 vs 2023)</div>
					</template>
					<div class="chart-container">
						<e-charts :option="costComparisonOption" />
					</div>
				</el-card>
			</el-col>
		</el-row>

		<el-row :gutter="20" class="mb-20">
			<!-- 成本趋势分析 -->
			<el-col :span="12">
				<el-card>
					<template #header>
						<div class="chart-title">成本趋势分析</div>
					</template>
					<div class="chart-container">
						<e-charts :option="costTrendOption" />
					</div>
				</el-card>
			</el-col>

			<!-- 成本异常分析 -->
			<el-col :span="12">
				<el-card>
					<template #header>
						<div class="chart-title">成本异常分析</div>
					</template>
					<div class="chart-container">
						<e-charts :option="costAnomalyOption" />
					</div>
				</el-card>
			</el-col>
		</el-row>
	</div>
</template>

<script setup>
	import { ref, onMounted, computed } from "vue";
	import ECharts from "@/components/ECharts";
	import { use } from "echarts/core";
	import { CanvasRenderer } from "echarts/renderers";
	import { PieChart, BarChart, LineChart } from "echarts/charts";
	import {
		TitleComponent,
		TooltipComponent,
		LegendComponent,
		GridComponent,
	} from "echarts/components";
	import {
		getCostCategoryList,
		getCostStatistics,
		getCostPeriodOptions,
		getCostComposition,
		getCostTrend,
		getCostComparison,
		getCostAbnormal,
		getCostDetails,
	} from "@/api/prod_operate/synthesis/cost/analysis";

	use([
		CanvasRenderer,
		PieChart,
		BarChart,
		LineChart,
		TitleComponent,
		TooltipComponent,
		LegendComponent,
		GridComponent,
	]);

	// 筛选表单
	const filterForm = ref({
		dateRange: [],
		costTypes: [],
	});

	// 时间范围类型 (1-本月 2-本季 3-本年)
	const timeRangeType = ref(1);

	// 成本类型下拉选项
	const costTypeOptions = ref([]);

	// 成本统计数据
	const costStats = ref([]);

	// 表格数据
	const tableData = ref([]);
	const loading = ref(false);
	const total = ref(0);

	// 分页控制
	const currentPage = ref(1);
	const pageSize = ref(10);

	// 图表配置
	const costCompositionOption = ref({});
	const costComparisonOption = ref({});
	const costTrendOption = ref({});
	const costAnomalyOption = ref({});

	// 初始化数据
	const initData = async () => {
		try {
			// 获取成本类型下拉列表
			const categoryRes = await getCostCategoryList();
			costTypeOptions.value = categoryRes.data.map((item) => ({
				dictValue: item.dictValue,
				dictLabel: item.dictLabel,
			}));

			// 获取成本统计数据
			await fetchCostStatistics();

			// 获取成本构成数据
			await fetchCostComposition();

			// 获取成本对比数据
			await fetchCostComparison();

			// 获取成本趋势数据
			await fetchCostTrend();

			// 获取成本异常数据
			await fetchCostAbnormal();
		} catch (error) {
			console.error("初始化数据失败:", error);
		}
	};

	// 获取成本统计数据
	const fetchCostStatistics = async () => {
		try {
			const params = {
				startTime: filterForm.value.dateRange?.[0],
				endTime: filterForm.value.dateRange?.[1],
				costType: filterForm.value.costTypes.join(","),
			};
			const res = await getCostStatistics(params);
			costStats.value = res.data;
		} catch (error) {
			console.error("获取成本统计失败:", error);
		}
	};

	// 获取成本构成数据
	const fetchCostComposition = async () => {
		try {
			const res = await getCostComposition({ type: timeRangeType.value });
			const data = res.data;

			costCompositionOption.value = {
				tooltip: {
					trigger: "item",
					formatter: "{a} <br/>{b}: {c} ({d}%)",
				},
				legend: {
					orient: "vertical",
					right: 10,
					top: "center",
					data: data.map((item) => item.name),
				},
				series: [
					{
						name: "成本构成",
						type: "pie",
						radius: ["50%", "70%"],
						avoidLabelOverlap: false,
						itemStyle: {
							borderRadius: 10,
							borderColor: "#fff",
							borderWidth: 2,
						},
						label: {
							show: false,
							position: "center",
						},
						emphasis: {
							label: {
								show: true,
								fontSize: "18",
								fontWeight: "bold",
							},
						},
						labelLine: {
							show: false,
						},
						data: data.map((item) => ({
							value: item.value,
							name: item.name,
						})),
					},
				],
			};
		} catch (error) {
			console.error("获取成本构成失败:", error);
		}
	};

	// 获取成本对比数据
	// 获取成本对比数据（支持月份/季度/年度切换）
	const fetchCostComparison = async () => {
		try {
			const res = await getCostComparison({ type: timeRangeType.value });
			const data = res.data; // 直接取接口返回的data数组

			// 根据时间类型动态设置图例名称
			let legendNames = [];
			switch (timeRangeType.value) {
				case 1: // 月份对比
					legendNames = ["上月", "本月"];
					break;
				case 2: // 季度对比
					legendNames = ["上季度", "本季度"];
					break;
				case 3: // 年度对比
					legendNames = ["上一年度", "本年度"];
					break;
				default:
					legendNames = ["对比项1", "对比项2"];
			}

			// 提取成本项（y轴类目）
			const costItems = data.map((item) => item.costItem);

			// 图表配置
			costComparisonOption.value = {
				tooltip: {
					trigger: "axis",
					axisPointer: { type: "shadow" },
					formatter: "{b}<br/>{a}: {c.toFixed(2)} 元", // 显示金额并保留两位小数
				},
				legend: {
					data: legendNames,
					top: 0, // 图例置顶，避免遮挡
				},
				grid: {
					left: "10%", // 增加左侧距离，防止文字截断
					right: "4%",
					bottom: "3%",
					containLabel: true,
				},
				xAxis: {
					type: "value",
					boundaryGap: [0, 0.01],
					axisLabel: { formatter: "{value} 元" }, // 显示金额单位
				},
				yAxis: {
					type: "category",
					data: costItems,
					axisLabel: {
						// 长文本自动换行
						interval: 0,
						formatter: (value) => {
							if (value.length > 5) {
								return value.slice(0, 5) + "\n" + value.slice(5);
							}
							return value;
						},
					},
				},
				series: [
					{
						name: legendNames[0], // 对应上一周期（上月/上季度/上一年）
						type: "bar",
						data: data.map((item) => item.costPrev),
						itemStyle: { color: "#409EFF" },
					},
					{
						name: legendNames[1], // 对应本周期（本月/本季度/本年度）
						type: "bar",
						data: data.map((item) => item.costCurrent),
						itemStyle: { color: "#67C23A" },
					},
				],
			};
		} catch (error) {
			console.error("获取成本对比失败:", error);
			// 错误时显示空图表
			costComparisonOption.value = {
				tooltip: {},
				legend: { data: [] },
				grid: { containLabel: true },
				xAxis: { type: "value" },
				yAxis: { type: "category", data: [] },
				series: [],
			};
		}
	};

	// 获取成本趋势数据
	const fetchCostTrend = async () => {
		try {
			const res = await getCostTrend({ type: timeRangeType.value });
			const data = res.data;

			costTrendOption.value = {
				tooltip: {
					trigger: "axis",
				},
				legend: {
					data: data.series.map((item) => item.name),
				},
				grid: {
					left: "3%",
					right: "4%",
					bottom: "3%",
					containLabel: true,
				},
				xAxis: {
					type: "category",
					boundaryGap: false,
					data: data.dateList,
				},
				yAxis: {
					type: "value",
				},
				series: data.series.map((item) => ({
					name: item.name,
					type: "line",
					data: item.data,
				})),
			};
		} catch (error) {
			console.error("获取成本趋势失败:", error);
		}
	};

	// 获取成本异常数据
	const fetchCostAbnormal = async () => {
		try {
			const res = await getCostAbnormal({ type: timeRangeType.value });
			const data = res.data;

			costAnomalyOption.value = {
				tooltip: {
					trigger: "axis",
					axisPointer: {
						type: "shadow",
					},
				},
				xAxis: {
					type: "category",
					data: data.map((item) => item.abnormalName),
				},
				yAxis: {
					type: "value",
				},
				series: [
					{
						name: "异常金额",
						type: "bar",
						data: data.map((item) => item.count),
						itemStyle: {
							color: function (params) {
								const colorList = [
									"#c23531",
									"#2f4554",
									"#61a0a8",
									"#d48265",
									"#91c7ae",
								];
								return colorList[params.dataIndex % colorList.length];
							},
						},
					},
				],
			};
		} catch (error) {
			console.error("获取成本异常失败:", error);
		}
	};

	// 获取成本明细数据
	const fetchCostDetails = async () => {
		try {
			loading.value = true;
			const params = {
				startTime: filterForm.value.dateRange?.[0],
				endTime: filterForm.value.dateRange?.[1],
				costType: filterForm.value.costTypes.join(","),
				pageNum: currentPage.value,
				pageSize: pageSize.value,
			};
			const res = await getCostDetails(params);
			console.log(res);

			tableData.value = res.data;
			total.value = res.total;
		} catch (error) {
			console.error("获取成本明细失败:", error);
		} finally {
			loading.value = false;
		}
	};

	// 时间范围变化处理
	const handleDateChange = () => {
		handleQuery();
	};

	// 成本类型变化处理
	const handleTypeChange = () => {
		handleQuery();
	};

	// 时间范围类型变化处理
	const handleTimeRangeChange = () => {
		// 获取成本构成数据
		fetchCostComposition();

		// 获取成本对比数据
		fetchCostComparison();

		// 获取成本趋势数据
		fetchCostTrend();

		// 获取成本异常数据
		fetchCostAbnormal();
	};

	// 查询处理
	const handleQuery = () => {
		currentPage.value = 1;
		fetchCostStatistics();
		fetchCostDetails();
	};

	// 重置处理
	const handleReset = () => {
		filterForm.value = {
			dateRange: [],
			costTypes: [],
		};
		timeRangeType.value = 1;
		handleQuery();
	};

	// 分页大小变化
	const handleSizeChange = (val) => {
		pageSize.value = val;
		fetchCostDetails();
	};

	// 当前页变化
	const handleCurrentChange = (val) => {
		currentPage.value = val;
		fetchCostDetails();
	};

	// 初始化
	onMounted(() => {
		initData();
	});
</script>

<style scoped>
	.app-container {
		padding: 20px;
		background-color: #f5f7fa;
	}

	.mb-20 {
		margin-bottom: 20px;
	}

	.mt-20 {
		margin-top: 20px;
	}

	.card-content {
		text-align: center;
		padding: 15px 0;
	}

	.card-title {
		font-size: 16px;
		color: #909399;
		margin-bottom: 10px;
	}

	.card-value {
		font-size: 24px;
		font-weight: bold;
		color: #303133;
		margin-bottom: 5px;
	}

	.card-compare {
		font-size: 14px;
		color: #67c23a;
	}

	.card-compare.negative {
		color: #f56c6c;
	}

	.chart-title {
		font-size: 16px;
		font-weight: bold;
		color: #303133;
	}

	.chart-container {
		width: 100%;
	}

	.table-title {
		font-size: 16px;
		font-weight: bold;
		color: #303133;
	}

	.positive {
		color: #67c23a;
	}

	.negative {
		color: #f56c6c;
	}
</style>
